<template>
  <view class="leave-detail-page">
    <view class="page-header">
      <text class="page-title">请假申请详情</text>
      <view class="header-actions">
        <button class="btn btn-default" @click="handleBack">返回</button>
        <button class="btn btn-primary" @click="handleEdit" v-if="leave.status === 1">编辑</button>
        <button class="btn btn-success" @click="handleApprove" v-if="leave.status === 1">批准</button>
        <button class="btn btn-danger" @click="handleReject" v-if="leave.status === 1">拒绝</button>
      </view>
    </view>

    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <view v-else class="detail-content">
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">申请信息</text>
          <view :class="['status-badge', getStatusClass(leave.status)]">
            {{ getStatusText(leave.status) }}
          </view>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">申请人</text>
            <text class="value highlight">{{ leave.requester_name || leave.requester_id || '-' }}</text>
          </view>
          
          <view class="detail-row" v-if="leave.requester_role_text">
            <text class="label">申请人职务</text>
            <text class="value">{{ leave.requester_role_text }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">请假类型</text>
            <text class="value">{{ getLeaveTypeText(leave.leave_type) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">开始日期</text>
            <text class="value">{{ leave.start_date || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">结束日期</text>
            <text class="value">{{ leave.end_date || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">请假天数</text>
            <text class="value highlight">{{ leave.duration_days || 0 }} 天</text>
          </view>
          
          <view class="detail-row vertical">
            <text class="label">请假原因</text>
            <text class="value">{{ leave.reason || '-' }}</text>
          </view>
        </view>
      </view>

      <view class="detail-card" v-if="leave.status !== 1">
        <view class="card-header">
          <text class="card-title">审批信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row" v-if="leave.approved_by">
            <text class="label">批准人</text>
            <text class="value">{{ leave.approver_name || leave.approved_by || '-' }}</text>
          </view>
          
          <view class="detail-row" v-if="leave.approved_time">
            <text class="label">批准时间</text>
            <text class="value">{{ formatTime(leave.approved_time) }}</text>
          </view>
          
          <view class="detail-row vertical" v-if="leave.rejection_reason">
            <text class="label">拒绝原因</text>
            <text class="value">{{ leave.rejection_reason }}</text>
          </view>
        </view>
      </view>

      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">时间信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">创建时间</text>
            <text class="value">{{ formatTime(leave.create_time) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">更新时间</text>
            <text class="value">{{ formatTime(leave.update_time) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

const loading = ref(true)
const leaveId = ref('')
const leave = reactive({
  requester_id: '',
  requester_name: '',
  requester_role_text: '',
  leave_type: 1,
  start_date: '',
  end_date: '',
  duration_days: 0,
  reason: '',
  status: 1,
  approved_by: '',
  approver_name: '',
  approved_time: null,
  rejection_reason: '',
  create_time: null,
  update_time: null
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  leaveId.value = currentPage.options.id || ''
  
  if (!leaveId.value) {
    uni.showToast({ title: '缺少请假申请ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/leave_requests/list' })
    }, 1500)
    return
  }
  
  await loadLeaveData()
  loading.value = false
})

async function loadLeaveData() {
  try {
    // 调用云对象方法获取请假申请信息
    const leaveRequestsObj = uniCloud.importObject('dh-leave_requests')
    const result = await leaveRequestsObj.getLeaveRequestById(leaveId.value)
    
    if (result.code === 200 && result.data) {
      Object.assign(leave, result.data)
    } else {
      throw new Error(result.message || '请假申请不存在')
    }
  } catch (err) {
    console.error('加载请假数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/leave_requests/list' })
    }, 1500)
  }
}

function getLeaveTypeText(type) {
  const types = {
    1: '病假',
    2: '年假',
    3: '事假',
    4: '其他'
  }
  return types[type] || '未知'
}

function getStatusText(status) {
  const statusMap = {
    1: '待审批',
    2: '已批准',
    3: '已拒绝'
  }
  return statusMap[status] || '未知'
}

function getStatusClass(status) {
  const classMap = {
    1: 'status-pending',
    2: 'status-approved',
    3: 'status-rejected'
  }
  return classMap[status] || ''
}

function formatTime(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

function handleBack() {
  uni.redirectTo({ url: '/pages/business/leave_requests/list' })
}

function handleEdit() {
  uni.redirectTo({ url: `/pages/business/leave_requests/edit?id=${leaveId.value}` })
}

function handleApprove() {
  uni.showModal({
    title: '确认批准',
    content: '确定要批准这个请假申请吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '处理中...' })
          // 调用云对象方法批准请假申请
          const leaveRequestsObj = uniCloud.importObject('dh-leave_requests')
          const uniIdToken = uni.getStorageSync('uni_id_token') || {}
          const result = await leaveRequestsObj.approveLeaveRequest(
            leaveId.value,
            uniIdToken.uid || '',
            uniIdToken.username || '管理员'
          )
          uni.hideLoading()
          if (result.code === 200) {
            uni.showToast({ title: result.message || '批准成功', icon: 'success' })
          } else {
            uni.showToast({ title: result.message || '批准失败', icon: 'none' })
            return
          }
          setTimeout(() => {
            loadLeaveData()
          }, 1500)
        } catch (err) {
          console.error('批准失败:', err)
          uni.hideLoading()
          uni.showToast({ title: err.message || '批准失败', icon: 'none' })
        }
      }
    }
  })
}

function handleReject() {
  uni.showModal({
    title: '拒绝申请',
    editable: true,
    placeholderText: '请输入拒绝原因',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '处理中...' })
          // 调用云对象方法拒绝请假申请
          const leaveRequestsObj = uniCloud.importObject('dh-leave_requests')
          const result = await leaveRequestsObj.rejectLeaveRequest(
            leaveId.value,
            res.content || '未填写原因'
          )
          uni.hideLoading()
          if (result.code === 200) {
            uni.showToast({ title: result.message || '拒绝成功', icon: 'success' })
          } else {
            uni.showToast({ title: result.message || '拒绝失败', icon: 'none' })
            return
          }
          uni.hideLoading()
          uni.showToast({ title: '已拒绝', icon: 'success' })
          setTimeout(() => {
            loadLeaveData()
          }, 1500)
        } catch (err) {
          console.error('拒绝失败:', err)
          uni.hideLoading()
          uni.showToast({ title: err.message || '操作失败', icon: 'none' })
        }
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.leave-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.page-header {
  background: #fff;
  padding: 30rpx 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
}

.btn {
  padding: 12rpx 24rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  white-space: nowrap;
  min-width: 100rpx;
  text-align: center;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
  
  &.btn-success {
    background: #4caf50;
    color: #fff;
  }
  
  &.btn-danger {
    background: #ff3b30;
    color: #fff;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .btn {
    flex: 1;
    min-width: 0;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.detail-content {
  flex: 1;
  padding: 20rpx;
}

.detail-card {
  background: #fff;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  background: #fafafa;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.status-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  
  &.status-pending {
    background: #fff3e0;
    color: #e65100;
  }
  
  &.status-approved {
    background: #e8f5e9;
    color: #2e7d32;
  }
  
  &.status-rejected {
    background: #ffebee;
    color: #c62828;
  }
}

.card-body {
  padding: 32rpx;
}

.detail-row {
  display: flex;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &.vertical {
    flex-direction: column;
  }
}

.label {
  font-size: 28rpx;
  color: #999;
  min-width: 180rpx;
  margin-bottom: 8rpx;
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  word-break: break-all;
  
  &.highlight {
    font-size: 36rpx;
    font-weight: bold;
    color: #007aff;
  }
}
</style>
